#include <string.h>
#include <hwicodec_common.h>

int hwicodec_pf_jpegd_init_bpool(hwicodec_t *h, hwicodec_soc_binfo_t *pbinfo)
{
	int encnum = 0, bsnum = 0, dmanum = 0;
	int y_encsize = 0, bssize = 0, dmasize = 0;
	hwicodec_jpegd_param_t *param = &h->param.param.jpegd_param;
	hwicodec_soc_bpool_t *bpool = &h->soc.bpool;
	int width = C_ALIGN(param->i_max_width, 16);
	int height = C_ALIGN(param->i_max_height, 16);
	hwicodec_mmcut_t mmcut[C_CHN_NUM_MAX * C_VB_NUM_MAX];
	int mcidx = 0, i = 0;

	bpool->vb_num = C_SOC_VB_MAX;
	bpool->vbinfo[C_SOC_VB_ENC].type = C_SOC_VB_ENC;
	encnum = bpool->vbinfo[C_SOC_VB_ENC].num = 1;
	bpool->vbinfo[C_SOC_VB_BS].type = C_SOC_VB_BS;
	bsnum = bpool->vbinfo[C_SOC_VB_BS].num = 1;
	bpool->vbinfo[C_SOC_VB_DMA].type = C_SOC_VB_DMA;
	dmanum = bpool->vbinfo[C_SOC_VB_DMA].num = 1;
	bpool->buf_num = encnum + bsnum + dmanum;
	y_encsize = hwicodec_cal_bufsize(h, &pbinfo[C_SOC_VB_ENC], width, height);
	bssize = hwicodec_cal_bufsize(h, &pbinfo[C_SOC_VB_BS], width, height);
	dmasize = hwicodec_cal_bufsize(h, &pbinfo[C_SOC_VB_DMA], width, height);
	bpool->buf_size = (y_encsize*3/2+C_NATIVE_ALIGN)*encnum + bssize*bsnum + dmasize*dmanum;

	if ((bpool->buf_base_v = (intptr_t)h->param.ckmalloc(-1, bpool->buf_size, C_VB_ALIGN)) == 0) {
		hwicodec_log(h, C_LOG_ERROR, "malloc buf_base size:%d failed\n", bpool->buf_size);
		goto err_malloc_buf_base;
	}

	memset(mmcut, 0, sizeof(hwicodec_mmcut_t));
	for (i = 0; i < encnum; i++, mcidx++) {
		mmcut[mcidx].type = C_SOC_VB_ENC;
		mmcut[mcidx].size = c_align(y_encsize * 3 / 2, pbinfo[C_SOC_VB_ENC].align,
				pbinfo[C_SOC_VB_ENC].disalign);
		mmcut[mcidx].ysize = y_encsize;
	}

	for (i = 0; i < bsnum; i++, mcidx++) {
		mmcut[mcidx].type = C_SOC_VB_BS;
		mmcut[mcidx].size = bssize;
		mmcut[mcidx].ysize = 0;
	}

	for (i = 0; i < dmanum; i++, mcidx++) {
		mmcut[mcidx].type = C_SOC_VB_DMA;
		mmcut[mcidx].size = dmasize;
		mmcut[mcidx].ysize = 0;
	}

	if (mcidx != bpool->buf_num) {
		hwicodec_log(h, C_LOG_ERROR, "mcidx err\n");
		goto err_mcidx;
	}

	if(hwicodec_init_soc_bpool(h, pbinfo, mmcut, width, height, param->b_tlb) < 0) {
		hwicodec_log(h, C_LOG_ERROR, "init_soc_bpool\n");
		goto err_init_soc_bpool;
	}

	return 0;

err_init_soc_bpool:
err_mcidx:
	h->param.ckfree(-1, (void *)bpool->buf_base_v);
err_malloc_buf_base:
	return -1;
}
